import logging
import os

from flask import Flask
from flask_environments import Environments
from logging.handlers import RotatingFileHandler

import config

app = Flask(__name__)

# 加载配置
env = Environments(app)
env.from_object(config.Config)

# 记录日志
handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=1)
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
handler.setLevel(logging.WARNING)
app.logger.addHandler(handler)

# 初始化数据库及相关资源
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
db_session = db.session
db_engine = db.engine
from . import models


if not os.path.exists(__file__.replace("\\","/")[:-11]+app.config.get("DB").DATABASE+".db"):
    print(__file__.replace("\\","/")[:-11]+app.config.get("DB").DATABASE+".db")
    db.create_all()

# 初始化爬虫
from .catcher import wm168  as wm 
wm.init("ckzidong1","qwe123","023510",app.config['BASEURI'])


if app.config.get("DEBUG",True):
    wm.setCookies(app.config.get("COOKIES",{}))
else:
    print("_____________LOGIN")
    wm.login()

# 引入 views 层
from . import views
from . import event_loop

#unlocker = event_loop.UnLocker()